package com.tomasio.projects.lua.controllers;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import com.tomasio.projects.lua.api.MainService;
import com.tomasio.projects.lua.core.exception.CoreException;
import com.tomasio.projects.lua.forms.GroupForm;
import com.tomasio.projects.lua.forms.SelectApplicationForm;
import com.tomasio.projects.lua.model.Application;
import com.tomasio.projects.lua.model.Group;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 *
 * @author dctp
 */
@Controller
@RequestMapping("/groups")
public class GroupsController {

    private final MainService mainService;

    @Autowired
    public GroupsController(MainService mainService) {
        this.mainService = mainService;
    }

    @RequestMapping({"/", "/index", ""})
    public String index(Model model, SelectApplicationForm form,
            BindingResult bindingResult, WebRequest request) {

        if (form.getApplicationUID() == null
                || form.getApplicationUID().isEmpty()) {
            return "redirect:groups/select_application";
        }
        
        Application application = mainService.findApplication(form.getApplicationUID());

        // listar apenas grupos da aplicação selecionada;
        List<Map<Object, Object>> dataList = new ArrayList<Map<Object, Object>>();

        List<Group> groups = mainService.listGroups(application.getUid());

        for (Group group : groups) {
            Map<Object, Object> item = new HashMap<Object, Object>();

            item.put("name", group.getName());
            item.put("description", group.getDescription());

            dataList.add(item);
        }

        model.addAttribute("total", dataList.size());
        model.addAttribute("dataList", dataList);

        return "groups";
    }

    
    @RequestMapping("/select_application")
    public String selectApplication(Model model, WebRequest request) {
        List<Application> applications = mainService.listApplications();
        Map<String, String> selectableApplications = new HashMap<String, String>();
        
        selectableApplications.put(null, " ");
        for (Application application : applications) {
            selectableApplications.put(application.getName(), application.getName());
        }
        model.addAttribute(new SelectApplicationForm());
        model.addAttribute("selectableApplications", selectableApplications);
        return "groups/select_application";
    }

    @RequestMapping("/new")
    public String newGroup(Model model) {
        GroupForm form = new GroupForm();
        model.addAttribute(form);
        return "groups/form";
    }

    @RequestMapping("/edit")
    public String editGroup(Model model, WebRequest request) {
        GroupForm form = new GroupForm();
        String uidParam = request.getParameter("uid");
        if (uidParam == null) {
            return "redirect:index";
        }

        Group group = mainService.findGroup(uidParam);
        form.setName(group.getName());
        form.setDescription(group.getDescription());

        model.addAttribute(form);
        return "groups/form";
    }

    @RequestMapping("/save")
    public String saveGroup(Model model, @Valid GroupForm form,
            BindingResult bindingResult, WebRequest request) {

        if (bindingResult.hasErrors()) {
            return "groups/form";
        }

        Group group = new Group();
        group.setDescription(form.getDescription());
        group.setName(form.getName());

        try {
            if (group.getUid() == null) {
                String uid = mainService.createGroup(group);
                group.setUid(uid);
                model.addAttribute("successMessage", "Grupo adicionado com sucesso!");
            } else {
                mainService.updateGroup(group);
                model.addAttribute("successMessage", "Grupo atualizado com sucesso!");
            }

        } catch (CoreException ex) {
            model.addAttribute("errorMessage", ex.getMessage());
            return "groups/form";
        }

        model.addAttribute("data", group);

        return "groups/detail";

    }

    @RequestMapping("/detail")
    public String detailGroup(Model model, WebRequest request) {
        Map<Object, Object> data = new HashMap<Object, Object>();
        String uidParam = request.getParameter("uid");
        if (uidParam == null) {
            return "redirect:index";
        }

        Group group = mainService.findGroup(uidParam);

        model.addAttribute("data", group);
        return "groups/detail";
    }

    @RequestMapping("/remove")
    public String removeGroup(Model model, WebRequest request,
            final RedirectAttributes redirectAttributes) {
       
        String uidParam = request.getParameter("id");
        if (uidParam == null) {
            return "redirect:index";
        }

        try {
            mainService.removeGroup(uidParam);
            redirectAttributes.addFlashAttribute("successMessage", "Grupo foi removido com sucesso!");

        } catch (CoreException ex) {
            redirectAttributes.addFlashAttribute("errorMessage", ex.getMessage());
            return "redirect:index";
        }

        return "redirect:index";
    }
}
